// void, Obj me, Obj u

Unit this, tgt;
point pt;

Sleep(rand(100)+10);
this = me.AsUnit();

if (!.IsValid()) return;
if (!u.IsValid()) return;

if (.IsValid) {// leave parry mode at new command
	.SetParryMode(false);
	
	if(.hero.IsValid){
		if(.hero.HasItem("irage_battle")){
			Sleep(rand(200)+10);
			.AddCommand(true, "engage");
			return;
		} else if(.hero.HasItem("irage_battle_stand")){
			Sleep(rand(200)+10);
			.AddCommand(true, "stand_position");
			return;
		}
	}
	
	if(.item_count > 0){
		Item item;
		
		item = .FindItem("Terrain bonus I");
		if(item.IsValid)
			.RemoveItemsOfType("Terrain bonus I");
		else {
			item = .FindItem("Terrain bonus II");
			if(item.IsValid)
				.RemoveItemsOfType("Terrain bonus II");
			else {
				item = .FindItem("Terrain bonus III");
				if(item.IsValid)
					.RemoveItemsOfType("Terrain bonus III");
				else {
					item = .FindItem("Terrain bonus IV");
					if(item.IsValid)
						.RemoveItemsOfType("Terrain bonus IV");
				}
			}
		}
	}
}

//pr("unit::attack: attacking particular enemy");
tgt = u.AsUnit;
pt = u.posRH;

if(u.AsBuilding.IsValid){

	Sleep(rand(400) + 200);
	
    if(.IsHeirOf("EAxetrower")) return;
	if(.IsHeirOf("ISlinger")) return; 
	if(.IsHeirOf("RVelit")) return;
	if(.IsHeirOf("CJavelinThrower")) return;
	if(.IsHeirOf("CJavelinThrowerLongJavelin")) return;
	if(.IsHeirOf("BJavelineer")) return; 
	if(.IsHeirOf("THuntress")) return;
	if(!u.IsValid()) return; // buildings also can die (catapults)
}

if(.IsEnemy(u) || u.AsBuilding.IsValid){

	while(u.IsAlive() && .IsValidTarget(u)){
	
		if(!.IsEnemy(u) && !u.AsBuilding.IsValid)
			return;
			
		//.pr("unit::attack: going to enemy");
		if(.GotoAttack(u, 1500, true, 2500)){
			//pr("unit::attack: fighting");
			
			if(u.AsBuilding.IsValid){
				while(.Attack(u)){
					Sleep(2000+rand(5000));
				}
			} else {
				if(!u.IsMilitary){
					while(.Attack(u));
				} else {
					Sleep(rand(100)+100);
					.AddCommand(true, "advance", pt);
					.AddCommand(true, "engage_unit_type", tgt);
					return;
				}
			}
		}
	} 
}
Sleep(rand(100)+100);
.AddCommand(true, "engage_unit_type", tgt);
